package com.eduhzy.ttw.teacher.mvp.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ObjectUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.core.EventBusTags;
import com.eduhzy.ttw.commonsdk.core.RouterHub;
import com.eduhzy.ttw.commonsdk.entity.MineInfo;
import com.eduhzy.ttw.commonsdk.imgaEngine.GlideEngine;
import com.eduhzy.ttw.teacher.R;
import com.eduhzy.ttw.teacher.di.component.DaggerPersonInfoComponent;
import com.eduhzy.ttw.teacher.mvp.contract.PersonInfoContract;
import com.eduhzy.ttw.teacher.mvp.presenter.PersonInfoPresenter;
import com.eduhzy.ttw.teacher.mvp.ui.widget.ClipViewLayout;
import com.huantansheng.easyphotos.EasyPhotos;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.eduhzy.ttw.commonsdk.core.Constants.REQUEST_CODE_CHOOSE;
import static com.eduhzy.ttw.commonsdk.core.Constants.REQUEST_CROP_PHOTO;
import static com.eduhzy.ttw.commonsdk.core.Constants.ROUTER_INTEGER;
import static com.eduhzy.ttw.commonsdk.core.Constants.ROUTER_STRING;
import static com.jess.arms.utils.Preconditions.checkNotNull;

@Route(path = RouterHub.APP_PERSONINFOACTIVITY)
public class PersonInfoActivity extends BaseActivity<PersonInfoPresenter> implements PersonInfoContract.View {

    @BindView(R.id.iv_avatar)
    QMUIRadiusImageView ivAvatar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_gender)
    TextView tvGender;
    @Autowired(name = Constants.ROUTER_DATA)
    MineInfo mData;
    private QMUITipDialog uploadLoading;


    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerPersonInfoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_person_info; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        if (ObjectUtils.isNotEmpty(mData)) {
            Glide.with(this)
                    .load(mData.getTempAvatar())
                    .apply(RequestOptions.placeholderOf(R.drawable.img_touxiang).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL))
                    .into(ivAvatar);
            tvName.setText(mData.getRealName() == null ? "" : mData.getRealName());
            tvPhone.setText(mData.getMobile() == null ? "" : mData.getMobile());
            switch (mData.getGender()) {
                case 0:
                    tvGender.setText("未知");
                    break;
                case 1:
                    tvGender.setText("男");
                    break;
                case 2:
                    tvGender.setText("女");
                    break;
                default:

                    break;
            }
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @OnClick({R.id.avatar_layout, R.id.name_layout, R.id.phone_layout, R.id.gender_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.avatar_layout:
                uploadHeadImage();
                break;
            case R.id.name_layout:
                ARouter.getInstance().build(RouterHub.APP_PERSONUPDATEACTIVITY)
                        .withString(Intent.EXTRA_TITLE, Constants.MODIFY_NAME)
                        .withString(ROUTER_STRING, mData.getRealName())
                        .navigation();
                break;
            case R.id.phone_layout:
                ARouter.getInstance().build(RouterHub.APP_UPDATEPHONEACTIVITY)
                        .withString(Intent.EXTRA_TITLE, Constants.MODIFY_PHONE)
                        .withString(ROUTER_STRING, mData.getRealName())
                        .navigation();
                break;
            case R.id.gender_layout:
                ARouter.getInstance().build(RouterHub.APP_PERSONUPDATEACTIVITY)
                        .withString(Intent.EXTRA_TITLE, Constants.MODIFY_GENDER)
                        .withInt(ROUTER_INTEGER, mData.getGender())
                        .navigation();
                break;
            default:
        }
    }

    @Override
    public void showUploadLoading(boolean b) {
        if (uploadLoading == null) {
            uploadLoading = RxUtil.showLoading(this, "正在上传···");
        }
        if (b) {
            uploadLoading.show();
        } else {
            uploadLoading.dismiss();
        }
    }

    @Override
    public Context getActivity() {
        return this;
    }

    @Subscriber(tag = EventBusTags.PERSON_INFO)
    public void onEvents(Message msg) {
        switch (msg.what) {
            case EventBusTags.PERSON_UPDATE_SUCCESS:
                String name = (String) msg.obj;
                if (ObjectUtils.isNotEmpty(name)) {
                    mData.setRealName(name);
                    tvName.setText(name);
                }
                if (msg.arg1 > 0) {
                    if (msg.arg1 == 1) {
                        tvGender.setText("男");
                    } else {
                        tvGender.setText("女");
                    }
                    mData.setGender(msg.arg1);
                }
                EventBus.getDefault().post(msg, RouterHub.APP_MINEFRAGMENT);
                break;
            case EventBusTags.PHONE_UPDATE_SUCCESS:
                String phone = (String) msg.obj;
                if (ObjectUtils.isNotEmpty(phone)) {
                    mData.setMobile(phone);
                    tvPhone.setText(phone);
                }
                EventBus.getDefault().post(msg, RouterHub.APP_MINEFRAGMENT);
                break;
            default:
        }
    }

    /**
     * 上传头像
     */
    private void uploadHeadImage() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_popupwindow, null);
        TextView btnCarema = (TextView) view.findViewById(R.id.btn_camera);
        TextView btnCancel = (TextView) view.findViewById(R.id.btn_cancel);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        View parent = LayoutInflater.from(this).inflate(R.layout.fragment_mine, null);
        popupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        //popupWindow在弹窗的时候背景半透明
        final WindowManager.LayoutParams params = getWindow().getAttributes();
        params.alpha = 0.5f;
        getWindow().setAttributes(params);
        popupWindow.setOnDismissListener(() -> {
            params.alpha = 1.0f;
            getWindow().setAttributes(params);
        });

        btnCarema.setOnClickListener(v -> {
            EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                    .setFileProviderAuthority("com.eduhzy.ttw.teacher.app.contentprovider.TTWFileProvider")
                    .start(REQUEST_CODE_CHOOSE);
            popupWindow.dismiss();
        });
        btnCancel.setOnClickListener(v -> popupWindow.dismiss());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        switch (requestCode) {
            case REQUEST_CODE_CHOOSE:
                if (intent != null) {
                    List<String> photos = intent.getStringArrayListExtra(EasyPhotos.RESULT_PATHS);
                    for (String photo : photos) {
                        gotoClipActivity(Uri.fromFile(new File(photo)));
//                        ARouter.getInstance().build(Uri.fromFile(new File(photo))).
                    }
                }
                break;
            case REQUEST_CROP_PHOTO:  //剪切图片返回
                if (resultCode == RESULT_OK) {
                    final Uri uri = intent.getData();
                    if (uri == null) {
                        return;
                    }
                    String cropImagePath = ClipViewLayout.getRealFilePathFromUri(this, uri);
                    Glide.with(this)
                            .load(cropImagePath)
                            .apply(RequestOptions.placeholderOf(R.drawable.img_touxiang).centerCrop().diskCacheStrategy(DiskCacheStrategy.ALL))
                            .into(ivAvatar);
                    //此处后面可以将bitMap转为二进制上传后台网络
                    mPresenter.uploadAvatar(cropImagePath);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 打开裁减界面
     */
    public void gotoClipActivity(Uri uri) {
        if (uri == null) {
            return;
        }
        ARouter.getInstance()
                .build(RouterHub.APP_CLIPIMAGEACTIVITY)
                .withParcelable(Constants.ROUTER_DATA, uri)
                .withString(Intent.EXTRA_TITLE, "移动和缩放")
                .navigation(this, REQUEST_CROP_PHOTO);
    }

}
